import pickle
from io import BytesIO

from minio import Minio

class ObjectType:
    io = 1
    file = 2
    data = 3

class MinioDB:
    def __init__(self, config):
        self.config = config
        self.client = Minio(
            endpoint=config["endpoint"],
            access_key=config["access_key"],
            secret_key=config["secret_key"],
            secure=config["secure"],
        )
        self.bucket = config["bucket"]

    def put_object(self, filepath: object, file: object, obj_type: object = ObjectType.data) -> object:
        minio_file_path = str(filepath)
        if obj_type == ObjectType.data:
            filedata = BytesIO(pickle.dumps(file))
            self.client.put_object(self.bucket, minio_file_path, filedata, len(filedata.getvalue()))
        elif obj_type == ObjectType.io:
            filedata = BytesIO(file)
            self.client.put_object(self.bucket, minio_file_path, filedata, len(filedata.getvalue()))
        else:
            self.client.fput_object(self.bucket, minio_file_path, file)

    def get_object(self, minio_file_path):
        return self.client.get_object(self.bucket, minio_file_path)

    def del_object(self, minio_file_path):
        self.client.remove_object(self.bucket, minio_file_path)

    def list_objects(self, prefix):
        return self.client.list_objects(self.bucket, prefix=prefix, recursive=True)